#include "Game Commander.h"
#include "Globals.h"

HWND OpenWindow(const char* cszWinClassName, const char* cszWindowName,  int nCmdShow);
LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
POINT g_Point;

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	//Open the window
	HWND hWnd = OpenWindow("Green Lightning", "Minecarts and Geysers",nCmdShow);

	if(GAME::Engine()->Initialize(hWnd,hInstance,hPrevInstance,nCmdShow,lpCmdLine) != SUCCEED)
		return -1;

	MSG uMsg;
	memset ( &uMsg, 0, sizeof ( uMsg ) );

	while(uMsg.message != WM_QUIT)
	{

		//Gives the GAME engine control until its done one frame then returns control to translate windows messages
		if(GAME::Engine()->WORK(g_Point) != SUCCEED)
			return -1;
		while(PeekMessage(&uMsg,NULL,0,0,PM_REMOVE))
		{
			TranslateMessage(&uMsg);
			DispatchMessage(&uMsg);
		}


	}
	return uMsg.wParam;
}

LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	switch(uMsg)
	{
	case WM_LBUTTONDOWN:

		g_Point.x = (LONG) LOWORD(lParam);
		g_Point.y = (LONG) HIWORD(lParam);
		break;

	case WM_CLOSE:
		PostQuitMessage(0);
		break;
	}
	return DefWindowProc(hWnd, uMsg, wParam, lParam);
}

HWND OpenWindow ( const char* cszWinClassName, const char* cszWindowName, int nCmdShow )
{
	WNDCLASSEX wc;
	HWND hWnd;

	HINSTANCE hInstance = ::GetModuleHandle ( NULL );
	assert ( NULL != hInstance );

	wc.lpszClassName	= cszWinClassName;
	wc.cbSize			= sizeof ( WNDCLASSEX );
	wc.style			= CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc		= WindowProc;
	wc.hInstance		= hInstance;
	wc.hIcon			= NULL;
	wc.hIconSm			= NULL;
	wc.hCursor			= ::LoadCursor ( NULL, IDC_ARROW );
	wc.hbrBackground	= ( HBRUSH )::GetStockObject( BLACK_BRUSH );
	wc.lpszMenuName		= NULL;
	wc.cbClsExtra		= 0;
	wc.cbWndExtra		= 0;

	if ( 0 == RegisterClassEx ( &wc ) )
	{
		return NULL;
	}

	hWnd = ::CreateWindowEx ( NULL,
		cszWinClassName,
		cszWindowName,
		WS_OVERLAPPEDWINDOW,
		0, 0,
		SCREEN_WIDTH, SCREEN_HEIGHT,
		NULL, NULL, ::GetModuleHandle ( NULL ), NULL );
	ShowWindow ( hWnd, nCmdShow );
	UpdateWindow ( hWnd );
	return hWnd;
}